/**
 * Created by kevin on 16/3/20.
 */
app.controller('RecordsCtrl', ['$scope','$http','$state', function($scope,$http,$state) {
    $scope.records;
    requestServlet("viewRecords",{},function(rs){
        $scope.records = rs.list;
    },function(msg){});
}]);

app.controller('RecordsListCtrl', ['$scope','$http','$state','$stateParams','$modal', function($scope,$http,$state,$stateParams,$modal) {

    $scope.recordId = $stateParams.recordId;
    $scope.record;
    $scope.recordsFilters;
    $scope.recordsDetail;
    $scope.recordsDetailLists;
    $scope.startIndex=0;
    $scope.batchSize=0;
    $scope.isLoad=true;
    $scope.totalCount=0;

    $scope.getRecordDetailList = function(){
        var queryData = JSON.stringify({recordId:$scope.recordId,searchValue:$scope.searchValue,recordsFilters:$scope.recordsFilters,startIndex:$scope.startIndex});
        requestServlet("getRecordDetailList",{queryData:queryData},function(rs){
            $scope.records = rs;
            $scope.recordsDetail = rs.list;
            if($scope.startIndex==0) {
                $scope.recordsDetailLists = rs.list;
            }else{
                $scope.recordsDetailLists = $scope.recordsDetailLists.concat(rs.list);
            }
            if(rs.list.length<$scope.batchSize){
                $scope.isLoad = true;
            }else{
                $scope.isLoad = false;
            }
        },function(msg){});
    }

    requestServlet("getRecordDetail",{recordId:$scope.recordId},function(rs){
        $scope.record = rs["record"];
        $scope.recordsFilters = rs["recordsFilters"];
        $scope.batchSize = $scope.record.batchSize;
        $scope.getRecordDetailList();
    },function(msg){});

    $scope.scrollEvent= function(){
        $scope.startIndex = $scope.startIndex + $scope.batchSize;
        $scope.getRecordDetailList();
    }

    $scope.searchRecordDetailLists= function(e){
        var keycode = window.event?e.keyCode:e.which;
        if(keycode==13){
            $scope.startIndex=0;
            $scope.isLoad = true;
            $scope.getRecordDetailList();
        }
    }

    $scope.filter_option_active = function(selected){
        if(selected){
            return "active";
        }
    }
    $scope.select_radio_filter_option = function(filter_index,filter_option_index){
        var filter_options = $scope.recordsFilters[filter_index]["filter_options"];
        for(var i=0;i<filter_options.length;i++){
            if(filter_options[i]["row_index"]==filter_option_index&&!filter_options[i]["selected"]){
                filter_options[i]["selected"] = true;
            }else {
                filter_options[i]["selected"] = false;
            }
        }
        $scope.recordsFilters[filter_index]["filter_options"] = filter_options;
        $scope.startIndex=0;
        $scope.isLoad = true;
        $scope.getRecordDetailList();
    }

	$scope.addRecord = function(){
        var modalInstance = $modal.open({
			templateUrl: 'tpl/create_record_modal.html',
			controller: 'createRecordModalCtrl',
			size:"lg",
			resolve: {
				scope: function () {return $scope},
				record: function () {return $scope.record}
			}
		});
		modalInstance.result.then(function () {
			
		}, function () {
			//dismiss
		});
    }
	
}]);
app.controller('createRecordModalCtrl', ['$scope', '$modalInstance','$state','record', function($scope, $modalInstance,$state,record) {
  $scope.record = record;
  $scope.addSrc = record.add_url;
  window.addEventListener('message',function(e){
			var data = JSON.parse(e.data)
			if(data.type=="add"){
				$modalInstance.close();
				if(data.id!=null){
					window.location.href="/suite/app/index.html#/app/records/"+record.id+"/"+data.id
				}else{
					$state.reload();
				}
					
			}
	},false);
  $scope.ok = function () {
    $modalInstance.close();
  };
  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
}])

app.controller('RecordsListDetailCtrl', ['$scope','$http','$state','$stateParams', function($scope,$http,$state,$stateParams) {
    $scope.listDetailId = $stateParams.listdetailId;
    $scope.recordId = $stateParams.recordId;
    $scope.recordsDetailListDetail;
    requestServlet("getRecordDetailListDetail",{recordId:$scope.recordId,listDetailId:$scope.listDetailId},function(rs){
        $scope.recordsDetailListDetail = rs;
        $scope.listdetailSrc=$scope.recordsDetailListDetail.detail_url+"?id="+$scope.listDetailId;
        window.addEventListener('message',function(e){
			var data = JSON.parse(e.data)
            if(data.type=="setHeight"){
                $("#recordsListDetail").height(data.height)
                $("#recordsListDetail").parent().removeClass('div-loading')
            }
        },false);
    },function(msg){});
}]);
app.controller('NewsRecordsCtrl', ['$scope','$http','$state','$stateParams','toaster','$modal', function($scope,$http,$state,$stateParams,toaster,$modal) {
    moment.locale($scope.selectLangCode);
    $scope.documents  = [];
    $scope.docIds = [];
    $scope.isNewsEdit = false;
    $scope.newsEdit = function(){
        $scope.isNewsEdit=true;
        setTimeout(function(){
            $("#content").focus();
        },0)
    }
    $scope.$on('sendMessage', function(event, data) {
        $scope.newsEdit();
        $scope.selectedUserAndGroups=[data];
    });
    $scope.initDocuments = function(){
        $scope.documents = [];
        for (var i = 0; i < $scope.docIds.length; i++) {
            requestServlet("getDocumentInfo", {id: $scope.docIds[i]}, function (rs) {

                if(rs.mimeType=='image'){
                    $scope.documents.splice(0, 0, rs);
                }else{
                    $scope.documents.push(rs);
                }
            }, function (msg) {
            });
        }
    }
    $scope.initDocuments();
    $scope.cleanContent = function (content){
        if(content["folderId"]==9) {
            requestServlet("deleteContent", {id: content.id}, function () {
                var docIds = [];
                for (var i = 0; i < $scope.docIds.length; i++) {
                    if ($scope.docIds[i] != content.id) {
                        docIds.push($scope.docIds[i]);
                    }
                }
                $scope.docIds = docIds;
                $scope.initDocuments();
            }, function (msg) {
            });
        }else{
            var docIds = [];
            for (var i = 0; i < $scope.docIds.length; i++) {
                if ($scope.docIds[i] != content.id) {
                    docIds.push($scope.docIds[i]);
                }
            }
            $scope.docIds = docIds;
            $scope.initDocuments();
        }
    }

    $scope.selectedFile = function (thiss){
        $scope.$apply(function($scope) {
            toaster.pop("wait","common.prompt","common.documentUpLoadLoading",2000,null,function(){});
        });
        var flag = $(thiss).attr("flag");
        uploadFileById(thiss,function(rs){
            $scope.$apply(function($scope) {
                toaster.pop("success","common.prompt","common.documentSuccess",null,null,function(){});
                if(rs.list[0].mimeType=='image'){
                    $scope.docIds.splice(0, 0, rs.list[0].id);
                }else{
                    $scope.docIds.push(rs.list[0].id);
                }
                $scope.initDocuments();
            });
        })
    }
    //切换发布新闻类型
    $scope.news_type="notice";
    $scope.set_news_type = function(news_type){
        $scope.news_type = news_type;
        if($scope.news_type=='messages'){
            if($scope.selectedUserAndGroups.length<1){
                $scope.selectUsers();
            }
        }else{
            if($scope.userSelectShow&&$scope.news_type=="notice"){
                $scope.userSelectShow=false;
                $scope.selectedUserAndGroups=[];
            }
        }
    }
    $scope.selectedUserAndGroups=[];
    if($stateParams.userId!=null&&$stateParams.userId!=-1) {
        requestServlet("getUserInfo",{user:$stateParams.userId},function(rs){
            var selectedUserAndGroup = {id:rs.userName,name:rs.firstName,type:"user"};
            $scope.selectedUserAndGroups.push(selectedUserAndGroup);
            $scope.userSelectShow=true;
            $scope.news_type="messages";
        },function(msg){});
    }
    $scope.selectUsers = function(){
        var modalInstance = $modal.open({
            templateUrl: 'tpl/select_users_modal.html',
            controller: 'selectUsersModalCtrl',
            resolve: {
                scope: function () {return $scope},
                selectedUserAndGroups: function () {return $scope.selectedUserAndGroups}
            }
        });
        modalInstance.result.then(function (selectedUserAndGroups) {
            $scope.selectedUserAndGroups=[];
            if(selectedUserAndGroups.length>0){
                $scope.userSelectShow=true;
                $scope.news_type="messages";
            }else{
                $scope.userSelectShow=false;
                $scope.news_type="notice";
            }
            for (var i=0;i<selectedUserAndGroups.length;i++){
                $scope.selectedUserAndGroups.push(selectedUserAndGroups[i]);
            }

        }, function () {
            //dismiss
        });
    }
    $scope.cleanUser = function (selectedUserAndGroup){
        for (var i=0;i<$scope.selectedUserAndGroups.length;i++){
            if($scope.selectedUserAndGroups[i].id==selectedUserAndGroup.id){
                $scope.selectedUserAndGroups.splice(i,1);
                break;
            }
        }
        if($scope.selectedUserAndGroups.length==0){
            $scope.userSelectShow=false;
            $scope.news_type="notice";
        }
    }
    //获取档案列表
    $scope.records;
    requestServlet("viewRecords",{},function(rs){
        $scope.records = rs.list;
    },function(msg){});
    //发布地理位置
    $scope.location="";$scope.address="";
    //切换新闻类型
    $scope.filterValue = "records";
    $scope.newsNavFilter = function(filter){
        if(filter==$scope.filterValue){
            return "active";
        }
    }
    $scope.setFilterValue = function(filter){
        $scope.startIndex=0;
        $scope.isLoad=false;
        $scope.filterValue = filter;
        $scope.getNews();
    }
    //查询新闻
    $scope.newss;$scope.startIndex=0;$scope.batchSize=25;
    $scope.isLoad=false;
    $scope.getNews = function(){
        requestServlet("viewNews",{startIndex:$scope.startIndex,batchSize:$scope.batchSize,searchType:$scope.filterValue,searchNewsText:$scope.searchNewsText,recordId:$scope.recordsDetailListDetail.recordId+"/"+$scope.recordsDetailListDetail.id},function(rs){
            if($scope.startIndex==0) {
                $scope.newss = rs.list;
            }else{
                $scope.newss = $scope.newss.concat(rs.list);
            }
            if(rs.list.length<$scope.batchSize){
                $scope.isLoad = true;
            }
        },function(msg){});
    }
    $scope.getNews();
    //搜索新闻
    $scope.searchNews= function(e){
        var keycode = window.event?e.keyCode:e.which;
        if(keycode==13){
            $scope.startIndex=0;
            $scope.isLoad=false;
            $scope.getNews();
        }
    }
    $scope.clickSearchNews= function(){
        $scope.startIndex=0;
        $scope.isLoad=false;
        $scope.getNews();
    }
    //滚动刷新
    $scope.scrollEvent= function(){
        $scope.startIndex = $scope.startIndex + $scope.batchSize;
        $scope.getNews();
    }
    //浏览新闻标记
    $scope.browseNews = function(news_id,my_is_browse_news,my_is_browse_new_comment){
        if(my_is_browse_news==0||my_is_browse_new_comment==0){
            requestServlet("browseNews",{news_id:news_id},function(rs){
            },function(msg){});
        }
        $("#news"+news_id).unbind("mouseenter");
    }
    //展开全文
    $scope.showContentFull = function(row_index){
        $scope.newss[row_index]["is_content_cut"]=false;
        $scope.newss[row_index]["is_content_full"]=true;
    }
    //收起全文
    $scope.hideContentFull = function(row_index){
        $scope.newss[row_index]["is_content_full"]=false;
        $scope.newss[row_index]["is_content_cut"]=true;
    }
    //鼠标划过参与者图标显示参与者
    $scope.showParticipants = function(news_id,row_index){
        window.isLink = true;
        $("#addParticipants"+news_id).select2({
            language: "zh-CN",
            ajax: {
                url: "/suite/plugins/servlet/searchUserAndGroup",
                delay: 250,
                dataType: 'json',
                data: function (params) {
                    return {
                        searchValue: params.term, // search term
                        operator: 2,
                        searchType: 'user'
                    };
                },
                processResults: function (data, params) {
                    return {results: data}
                },
                cache: true
            },
            placeholder: "添加参与者",
            minimumInputLength: 1,
            templateResult: formatState,
            templateSelection: formatRepoSelection,
            open:function(){
            }
        });
        $("#addParticipants"+news_id).on('select2:open',function(){
            window.isDrop = true;
        }).on('select2:close',function(){
            window.isDrop = false;
        });
        //获取参与者
        if($scope.newss[row_index]["participants"]==null){
            requestServlet("viewParticipants",{news_id:news_id},function(rs){
                $scope.newss[row_index]["participants"]=rs.list;
            },function(msg){});
        }
        var participantsLinkXY =$("#participantsLink"+news_id).offset();
        if($(window).height()-(participantsLinkXY.top-$(document.body).scrollTop()+20)>300){
            $("#participantsPanel"+news_id).css("top",participantsLinkXY.top-100);
            $("#participantsPanel"+news_id).css("left",participantsLinkXY.left-100);
        }else{
            $("#participantsPanel"+news_id).css("top",participantsLinkXY.top-100-$scope.newss[row_index]["participants"].length*25);
            $("#participantsPanel"+news_id).css("left",participantsLinkXY.left-100);
        }
        $("#participantsPanel"+news_id).show();
    }
    //鼠标离开隐藏参与者
    $scope.hideParticipants = function(news_id){
        window.isLink = false;
        setTimeout(function() {
            if (!window.isMoveDiv) {
                $("#participantsPanel" + news_id).fadeOut();
            }
        },200)
    }
    //鼠标停留参与者面板显示参与者面板
    $scope.showParticipantsPanel = function(news_id){
        window.isMoveDiv = true;
        $("#participantsPanel"+news_id).stop().fadeIn('fast');
    }
    //鼠标离开参与者面板隐藏参与者面板
    $scope.hideParticipantsPanel = function(news_id){
        window.isMoveDiv = false;
        if (!window.isLink && !window.isDrop) {
            $("#participantsPanel"+news_id).stop().fadeOut();
        }
    }
    //添加参与者
    $scope.addParticipants = function(news_id,row_index){
        var participants = $("#addParticipants"+news_id).select2("data");
        console.log(participants.length);
        if(participants.length>0) {
            requestServlet("addParticipants",{news_id: news_id, addParticipantsData: JSON.stringify(participants)},function(rs){
                $("#addParticipants" + news_id).select2('val', "");
                for (var i = 0; i < rs.list.length; i++) {
                    $scope.newss[row_index]["participants"].push(rs.list[i]);
                }
                $scope.newss[row_index]["participant_count"] = $scope.newss[row_index]["participant_count"] + rs.list.length;
            },function(msg){});
        }
    }

    //新闻参与者锁切换
    $scope.is_lock=0
    $scope.is_lock_function=function(){
        if($scope.is_lock==0){
            $scope.is_lock=1;
        }else{
            $scope.is_lock=0;
        }
    }
    //获取流程模型信息
    $scope.processModelList =[];
    $scope.processModelSelectShow = false;
    $scope.showprocessModelSelect = function(){
        if($scope.processModelSelectShow&&$("#processModelInput").val()==null){
            $scope.processModelSelectShow=false;
        }else{
            if($scope.processModelList.length<1){
                requestServlet("getProcessModels",{},function(rs){
                    $scope.processModelList = rs.list;
                },function(msg){});
            }
            $scope.processModelSelectShow=true;
        }
    }
    $scope.cleanProcessModelSelect = function(){
        $('#processModelInput').select2().val(null).trigger('change');
        $scope.processModelSelectShow=false;
    }

    //发布新闻
    $scope.publisherNews = function()
    {
        if($("#content").val()==""){
            $("#content").focus();
            return false;
        }
        $scope.attachments = $scope.documents;
        $scope.participants = $scope.selectedUserAndGroups;
        $scope.processmodels = $("#processModelInput").select2("data");
        $scope.have_to_comment = 0;
        if ($("#have_to_comment:checked").length == 0) {
            $scope.have_to_comment = 0;
        } else {
            $scope.have_to_comment = 1;
        }
        $scope.newsData = {
            content: $scope.content,
            location:$scope.location,
            address:$scope.address,
            news_type:$scope.news_type,
            have_to_comment: $scope.have_to_comment,
            is_lock: $scope.is_lock,
            attachments:$scope.attachments,
            participants:$scope.participants,
            processmodels:$scope.processmodels,
            recodes:[{id:$scope.recordsDetailListDetail.recordId+"/"+$scope.recordsDetailListDetail.id,name:$scope.recordsDetailListDetail.recordName+" / "+$scope.recordsDetailListDetail.name,type:"custom"}]
        }
        requestServlet("newNews",{newsData:JSON.stringify($scope.newsData)},function(rs){
            $state.reload();
        },function(msg){});
    }
    //删除新闻
    $scope.deleteNews = function(news_id,row_index,alertText){
        $scope.openPromptModal("common.prompt","common.ifDelete",function(){
            requestServlet("deleteNews",{news_id:news_id},function(rs){
                $("#news"+news_id).animate({
                    width: 0,
                    height: 0,
                    padding: 0
                },1000,function(){
                    $("#news"+news_id).remove();
                    $scope.newss.splice(row_index,1);
                })
            },function(msg){});
        });
    }
    //内容的样式
    $scope.contentCss = function(have_to_comment){
        if(have_to_comment==1){
            return "text-crude";
        }
    }
    //是否收藏
    $scope.isFavorite = function(favorite,row_index){
        if(favorite==1){
            return "active";
        }
    }
    //收藏切换
    $scope.setFavorite = function(news_id,favorite,row_index){
        requestServlet("setFavorite",{is_favorite:favorite,news_id:news_id},function(rs){
            if($scope.filterValue!="favorite"){
                if (favorite == 1) {
                    $scope.newss[row_index]["favorite_count"]--;
                    $scope.newss[row_index]["favorite"] = 0;
                } else {
                    $scope.newss[row_index]["favorite_count"]++;
                    $scope.newss[row_index]["favorite"] = 1;
                }
            }else {
                $scope.getNews();
            }
        },function(msg){});
    }
    //显示评论输入
    $scope.showComment = function(id){
        $("#comment"+id).toggle();
        $("#commentText"+id).focus();
    }
    $scope.commentTextLeftCss = function(comment_count){
        if(comment_count>0){
            return "m-l-xxl";
        }
    }
    //显示全部评论
    $scope.viewAllComments = function(news_id,row_index){
        if($scope.newss[row_index]["is_show_comments"]==null||$scope.newss[row_index]["is_show_comments"]==0){
            $scope.newss[row_index]["is_show_comments"]=1;
        }else{
            $scope.newss[row_index]["is_show_comments"]=0;
        }
        requestServlet("viewComments",{news_id:news_id,is_show:$scope.newss[row_index]["is_show_comments"]},function(rs){
            $scope.newss[row_index]["comments"]=rs.list;
        },function(msg){});
    }
    $scope.commentAttachs={};
    $scope.selectedFileByComment = function (thiss){
        $scope.$apply(function($scope) {
            toaster.pop("wait","common.prompt","common.documentUpLoadLoading",2000,null,function(){});
        });
        var flag = $(thiss).attr("flag");
        var newsId = $(thiss).attr("newsId");
        uploadFileById(thiss,function(rs){
            $scope.$apply(function($scope) {
                toaster.pop("success","common.prompt","common.documentSuccess",null,null,function(){});
                if(rs.list[0].mimeType=='image'){
                    if($scope.commentAttachs[newsId]==null){
                        $scope.commentAttachs[newsId] = [rs.list[0]];
                    }else{
                        $scope.commentAttachs[newsId].splice(0, 0, rs.list[0]);
                    }
                }else{
                    if($scope.commentAttachs[newsId]==null){
                        $scope.commentAttachs[newsId] = [rs.list[0]];
                    }else{
                        $scope.commentAttachs[newsId].push(rs.list[0]);
                    }
                }
                console.log($scope.commentAttachs);
            });
        })
    }
    $scope.cleanCommentContent = function (content,newsId){
        if(content["folderId"]==9) {
            requestServlet("deleteContent", {id: content.id}, function () {
                $scope.commentAttachs[newsId]=null;
            }, function (msg) {
            });
        }else{
            $scope.commentAttachs[newsId]=null;
        }
    }
    //添加评论
    $scope.addComment = function(id,row_index){
        $scope.commentContent = $("#commentText"+id).val();
        if($scope.commentContent==""){
            $("#commentText"+id).focus();
            return;;
        }
        $scope.attachments=$scope.commentAttachs[id];
        $scope.commentData = {
            content: $scope.commentContent,
            news_id:id,
            attachments:$scope.attachments
        }
        requestServlet("newComment",{commentData:JSON.stringify($scope.commentData)},function(rs){
            if($scope.filterValue != "inComments") {
                if ($scope.newss[row_index]["comments"] == null) {
                    $scope.newss[row_index]["comments"] = [rs];
                } else {
                    $scope.newss[row_index]["comments"].splice(0, 0, rs);
                }
                $scope.newss[row_index]["comment_count"]++;
                $scope.newss[row_index]["my_comment_count"]++;
                $scope.newss[row_index]["have_to_comment"] = 0;
                $("#commentText" + id).val("");
                $scope.commentAttachs[id] = null;
                $("#comment" + id).hide();
            }else{
                $scope.getNews();
            }
        },function(msg){});
    }
    setTimeout(function(){
        $("#processModelInput").select2({
            language: "zh-CN",
            placeholder: $("#selectProcessModelText").val()
        });
    },0)
    //文件预览
    $scope.documentsView = function(id,attachments){
        if(attachments==null){
            attachments = $scope.documents
        }
        var documentIds=[];
        var documentId;
        var viewIndex =0;
        for(var i=0;i<attachments.length;i++){
            documentIds.push(attachments[i].id);
            if(attachments[i].id==id){
                documentId =  attachments[i].id;
                viewIndex = i;
            }
        }
        var modalInstance = $modal.open({
            templateUrl: 'tpl/documents_view_modal.html',
            controller: 'documentsViewModalCtrl',
            size: "docView",
            resolve: {
                type: function () {return "preview"},
                documentIds: function () {return documentIds},
                scope: function () {return $scope},
                viewIndex: function () {return viewIndex},
                documentId:function () {return documentId}
            }
        });
    }
}]);